package com.lucky.auth_boot.security;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lucky.auth_boot.exception.BusinessException;
import com.lucky.auth_boot.pojo.dto.UserDTO;
import com.lucky.auth_boot.pojo.po.UserPO;
import com.lucky.auth_boot.mapper.RolesMapper;
import com.lucky.auth_boot.mapper.UserMapper;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class UserServices implements UserDetailsService {
    @Resource
    RolesMapper rolesMapper;
    @Resource
    UserMapper userMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<UserPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        UserPO userPO = userMapper.selectOne(queryWrapper);
        if (Objects.isNull(userPO)) {
            throw new UsernameNotFoundException("账号或密码错误");
        }
        UserDTO user = new UserDTO();
        BeanUtils.copyProperties(userPO,user);
        user.setRoles(rolesMapper.getUserRoleById(user.getId()));
        return user;
    }
}
